import sys
from PyQt5 import QtCore
from PyQt5.QtCore import QThread, pyqtSignal

from appui4 import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QMessageBox, QFileDialog
from GetHostIP import HostIP
from threading import Thread
from socket import *


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.ui = Ui_MainWindow()

        DEFAULT_PORT = 4433 # 默认端口
        self.host_ip = HostIP().ip
        self.host_port = DEFAULT_PORT
        self.dest_ip = ''
        self.dest_port = 8800

        self.udpSocket = socket(AF_INET, SOCK_DGRAM)
        self.isListen = False
        self.count = 0
        self.initUi()
        self.buttonConnect()
        self.threadRecv = MyThread(self.udpSocket)

    def initUi(self):
        self.ui.setupUi(self)
        self.setWindowTitle('网络调试助手')
        self.ui.pushButton_2.setEnabled(False)
        self.ui.comboBox_2.addItem(self.host_ip)
        self.ui.lineEdit_6.setText(str(self.host_port))

    def buttonConnect(self):
        self.ui.pushButton_4.clicked.connect(self.saveLog)  # 保存日志文件
        self.ui.pushButton_3.clicked.connect(self.setSocket)  # socket相关设置
        self.ui.pushButton_6.clicked.connect(self.setRecvData)  # 开启socket

    def setRecvData(self):
        if self.isListen:
            self.isListen = False  # 停止接收
            self.ui.pushButton_6.setText('开启接收')
            print('停止接收')
            self.udpSocket.close()
            self.threadRecv.stop()
        else:
            if self.count:
                self.udpSocket = socket(AF_INET, SOCK_DGRAM)
            else:
                self.count += 1
            self.threadRecv.sig.connect(self.recvData)
            self.isListen = True  # 开启接收
            self.ui.pushButton_6.setText('停止接收')
            print('开启接收')
            self.threadRecv.start()

    def setSocket(self):
        self.host_ip = self.ui.comboBox_2.currentText()
        self.host_port = int(self.ui.lineEdit_6.text())
        self.dest_port = self.ui.lineEdit_3.text()
        self.udpSocket.bind(('', self.host_port))

    def recvData(self, data):
        self.ui.textBrowser.append(data)



    def saveLog(self):
        mainWindow = QMainWindow()
        msgBox = QMessageBox()
        filePath = QFileDialog.getSaveFileName(mainWindow, u'选择要保存的位置', './log.txt', '*')[0]
        if not filePath:
            return
        log = str(self.ui.textBrowser.toPlainText())
        with open(filePath, "a") as f:
            f.write(log)
        QMessageBox.information(msgBox, '提示', '保存成功!')


class MyThread(QThread):
    sig =  pyqtSignal(str)

    def __init__(self, udpSocket):
        super(MyThread, self).__init__()
        self.udpSocket = udpSocket

    def stop(self):
        self.udpSocket.close()

    def run(self):
        while True:
            info = self.udpSocket.recvfrom(1024)
            addr = info[1]
            msg = info[0].decode('gb2312')
            data = str((addr, msg))
            self.sig.emit(data)





class SocketHandler:
    def __init__(self):
        super(SocketHandler, self).__init__()
        self.udpSocket = socket(AF_INET, SOCK_DGRAM)
        self.local_port = 4433
        self.udpSocket.bind(('', self.local_port))

    def sendData(self, data, addr):
        self.udpSocket.sendto(data.encode("gb2312"), addr)

    def recvData(self):
        while True:
            rec_info = self.udpSocket.recvfrom(1024)
            addr = str(rec_info[1])
            data = rec_info[0].decode("gb2312")
            print(data)



if __name__ == '__main__':
    """
    s = SocketHandler()
    tr = Thread(target=s.recvData)
    ts = Thread(target=s.sendData, args=['hahhahha', ('192.168.0.104', 7788)])
    tr.start()
    ts.start()
    """
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    app.exec_()
